import time
import logging
import requests
from requests.exceptions import RequestException
from srun import SrunClient


USERNAME = "xxxxxx"
PASSWD = "xxxxxx"

# 设置日志记录
logging.basicConfig(
    filename=r'ping_baidu_log.txt', 
    level=logging.INFO, 
    format='%(asctime)s - %(levelname)s - %(message)s'
)

# 定义检查百度是否可访问的函数
def check_baidu():
    try:
        # 尝试发送 HTTP 请求，设置超时时间为 5 秒
        response = requests.get('https://www.baidu.com', timeout=5)
        # 如果状态码是 200，说明访问成功
        return response.status_code == 200
    except RequestException as e:
        logging.error(f"Request failed: {e}")
        return False

# 定义执行 netlogin 的函数
def execute_netlogin():
    try:
        # 执行 netlogin 命令
        srun_client = SrunClient(print_log=False)
        srun_client.username = USERNAME
        srun_client.passwd = PASSWD
        if srun_client.login():
            logging.info("Executed netlogin command successfully.")
        else:
            logging.info("Executed netlogin command Failed.")
    except Exception as e:
        logging.error(f"Failed to execute netlogin: {e}")

# 主循环
def main():
    while True:
        if check_baidu():
            logging.info("Baidu is reachable, no action needed.")
        else:
            logging.warning("Failed to reach Baidu, executing netlogin.")
            execute_netlogin()

        # 每隔 10 分钟执行一次
        time.sleep(600)

# 捕捉 KeyboardInterrupt 使得脚本可以优雅退出
if __name__ == "__main__":
    try:
        main()
    except KeyboardInterrupt:
        logging.info("Script terminated by user.")